package com.zidian.teacher.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zidian.teacher.R;
import com.zidian.teacher.adapter.QuestionnaiireAddAdapter;
import com.zidian.teacher.utils.GetUserInfo;
import com.zidian.teacher.utils.ToastUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

import com.zidian.teacher.bean.QuestionAddBean;
import com.zidian.teacher.common.Constant;
import com.zidian.teacher.common.ToolBarActivity;

/**
 * Created by Administrator on 2016/9/11 0011.
 */
public class QuestionAddActivity extends ToolBarActivity {

    @Bind(R.id.question_add_title)
    EditText questionAddTitle;
    @Bind(R.id.question_add_person)
    RelativeLayout questionAddPerson;
    @Bind(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @Bind(R.id.study)
    TextView study;
    private TextView confrim;
    private QuestionnaiireAddAdapter adapter;
    //    private List<Map<String, Object>> data = new ArrayList<>();
    private List<QuestionAddBean> questionAddBeanList = new ArrayList<>();
    private List<QuestionAddBean> adapterList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setToolbarView(R.layout.toolbar_both);
        setContentView(R.layout.activity_question_add);
        setTitle("新增问卷");
        ButterKnife.bind(this);
        confrim = (TextView) findViewById(R.id.toolbar_sure);
        initView();
    }

    private void initView() {

        questionAddBeanList = addQuestion(questionAddBeanList);
        adapterList = filtrateData(questionAddBeanList);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        adapter = new QuestionnaiireAddAdapter(this, adapterList);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(adapter);

        int x = adapter.getItemCount();

        ToastUtil.showToast(this, adapter.getItemCount() + "");


        //添加点击事件
        adapter.setOnItemClickListener(new QuestionnaiireAddAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

            }

            @Override
            public void onItemLongClick(View view, int position) {


            }
        });

        adapter.setOnFootItemClickListener(new QuestionnaiireAddAdapter.OnFootItemClickListener() {
            @Override
            public void onFootItemClick(int position) {
                questionAddBeanList.addAll(addQuestion(questionAddBeanList));
                adapterList.clear();
                adapterList.addAll(filtrateData(questionAddBeanList));
                adapter.notifyDataSetChanged();
            }
        });
        adapter.setOnItemFootItemClickListener(new QuestionnaiireAddAdapter.OnItemFootItemClickListener() {
            @Override
            public void onItemFootItemClick(int pId, int position) {
                questionAddBeanList.clear();
                questionAddBeanList.addAll(addQuestionItem(adapterList, pId));
                adapterList.clear();
                adapterList.addAll(filtrateData(questionAddBeanList));
                adapter.notifyDataSetChanged();

            }
        });
        adapter.setOnQuestionDeleteListener(new QuestionnaiireAddAdapter.OnQuestionDeleteListener() {
            @Override
            public void onQuestionDeletListener(int pId, int position) {
                questionAddBeanList.clear();
                questionAddBeanList.addAll(deleteQuestionItem(adapterList,position));
                adapterList.clear();
                adapterList.addAll(filtrateData(questionAddBeanList));
                adapter.notifyDataSetChanged();
            }
        });

        questionAddPerson.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent();
                intent.setClass(context, ClassListActivity.class);
                startActivityForResult(intent, 7000);


            }
        });


        confrim.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String json = getQuestionnaireResult();

                if (json.length() == 0) {
                    return;
                } else {
                    updataQuestion(json);
                }

            }
        });

    }


    private List<QuestionAddBean> filtrateData(List<QuestionAddBean> datas) {

        List<QuestionAddBean> mList = new ArrayList<>();

        for (int i = 0; i < datas.size(); i++) {
            mList.add(datas.get(i));
            for (int j = 0; j < datas.get(i).getChild().size(); j++) {
                if (j == datas.get(i).getChild().size() - 1) {
                    datas.get(i).getChild().get(j).setIsLastChild(true);
                } else {
                    datas.get(i).getChild().get(j).setIsLastChild(false);
                }
                mList.add(datas.get(i).getChild().get(j));
            }
        }


        return mList;
    }

    private List<QuestionAddBean> addQuestion(List<QuestionAddBean> datas) {
        int id;
        if (datas.size() == 0) {
            id = 0;
        } else {
            id = datas.get(datas.size() - 1).getId() + 1;
        }
        List<QuestionAddBean> list = new ArrayList<>();
        QuestionAddBean bean = new QuestionAddBean(-2, id, false, false);
        QuestionAddBean bean2 = new QuestionAddBean(id, -1, true, true);
        list.add(bean);
        list.get(0).getChild().add(bean2);
        return list;
    }

    /**
     * 添加问卷选项
     * @param datas
     * @param pId
     * @return
     */
    private List<QuestionAddBean> addQuestionItem(List<QuestionAddBean> datas, int pId) {
        List<QuestionAddBean> list = new ArrayList<>();
        QuestionAddBean bean2 = new QuestionAddBean(pId, -1, true, false);
        datas.add(bean2);

        for (QuestionAddBean bean : datas) {
            if (!bean.isChild()) {
                list.add(bean);
            }
        }

        for (QuestionAddBean bean : datas) {
            bean.getChild().clear();
            if (bean.isChild()) {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getId() == bean.getpId()) {
                        list.get(i).getChild().add(bean);
                    }
                }
            }
        }

        return list;
    }

    /**
     * 删除答案选项
     * @param data
     * @return
     */
    private List<QuestionAddBean> deleteQuestionItem(List<QuestionAddBean> data, int position) {
        List<QuestionAddBean> list = new ArrayList<>();
        data.remove(position);
        for (QuestionAddBean bean : data) {
            if (!bean.isChild()) {
                list.add(bean);
            }
        }

        for (QuestionAddBean bean : data) {
            bean.getChild().clear();
            if (bean.isChild()) {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getId() == bean.getpId()) {
                        list.get(i).getChild().add(bean);
                    }
                }
            }
        }
        return list;
    }

    private String getQuestionnaireResult() {
        List<QuestionAddBean> parent = new ArrayList<>();

        for (QuestionAddBean pitem : parent) {
            pitem.getChild().clear();
        }

        for (QuestionAddBean item : adapterList) {
            if (!item.isChild()) {
                parent.add(item);
            }
        }

        String json = "";

        try {
            JSONArray jsonarray = new JSONArray();
            for (int i = 0; i < parent.size(); i++) {
                String opition = "";
                String optionsDescribe = "";
                if (parent.get(i).getQuestionName() == null || parent.get(i).getQuestionName().length() == 0) {
                    Snackbar.make(study,"请输入问卷题目！",Snackbar.LENGTH_SHORT).show();
                    return "";
                } else {

                }


                for (int j = 0; j < parent.get(i).getChild().size() - 1; j++) {
                    if (parent.get(i).getChild().get(j).getItemName() == null || parent.get(i).getChild().get(j).getItemName().length() == 0) {
                        Snackbar.make(study,"请输入选项内容！",Snackbar.LENGTH_SHORT).show();
                        return "";
                    } else {
                        if (parent.get(i).getChild().size() < 3) {
                            Snackbar.make(study,"请至少输入2个选项！",Snackbar.LENGTH_SHORT).show();
                            return "";
                        }
                        if (parent.get(i).getChild().size() > 5) {
                            Snackbar.make(study,"最多输入5个选项！",Snackbar.LENGTH_SHORT).show();
                            return "";
                        }
                        if (j == 0) {
                            optionsDescribe = parent.get(i).getChild().get(j).getItemName();
                            opition = (j + 1) + "";
                        } else {
                            optionsDescribe += "!!" + parent.get(i).getChild().get(j).getItemName();
                            opition += "!!" + (j + 1) + "";
                        }

                    }

                }

                if (optionsDescribe.length() == 0) {
                    Snackbar.make(study,"至少添加2个选项！",Snackbar.LENGTH_SHORT).show();
                    return "";
                }

                JSONObject jsonObjAnswer = new JSONObject();//pet对象，json形式
                jsonObjAnswer.put("questionNumber", i + 1 + "");
                jsonObjAnswer.put("questionContent", parent.get(i).getQuestionName());
                jsonObjAnswer.put("options", opition);
                jsonObjAnswer.put("optionsDescribe", optionsDescribe);
                jsonObjAnswer.put("problemTypes", "选择题");
                jsonObjAnswer.put("couplingIndex", "");
                jsonarray.put(jsonObjAnswer);
            }

            if (questionAddTitle.getText().toString().trim().length() == 0) {
                Snackbar.make(study,"请输入问卷标题！",Snackbar.LENGTH_SHORT).show();
                return "";
            } else if (study.getText().toString().trim().length() == 0) {
                Snackbar.make(study,"请选择发布对象！",Snackbar.LENGTH_SHORT).show();
                return "";
            }

            JSONObject jsonObjResult = new JSONObject();
            jsonObjResult.put("publisherId", GetUserInfo.getTeacherId(context));
            jsonObjResult.put("releaseToWho", study.getText().toString().trim());
            jsonObjResult.put("publishObjects", "班级");
            jsonObjResult.put("questionnaireExplain", "教师发布");
            jsonObjResult.put("questionnaireTitle", questionAddTitle.getText().toString().trim());
            jsonObjResult.put("questionnaireResult", jsonarray);

            json = jsonObjResult.toString();

        } catch (JSONException e) {
            e.printStackTrace();
        }


        Log.e("T", json + "");
        return json;
    }

    private void updataQuestion(String json) {
        String loginUrl = Constant.URL_TEACHER + "Questionnaire/teacherInsertQuestionnaire";
        HashMap<String, String> map = new HashMap<>();
        map.put("questionnaire", json);
        map.put("teacherId", GetUserInfo.getTeacherId(context));
        map.put("token", GetUserInfo.getToken(context));


        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("E", e.toString());
                ToastUtil.showToast(context, "获取列表失败！");
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e("T", response);
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        ToastUtil.showToast(context, jsonObject.getString("message"));
                        return;
                    } else {
                        ToastUtil.showToast(context, "发布成功");
                        finish();
                        return;
                    }

                } catch (JSONException e) {

                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 7000) {
            if (resultCode == 7001) {
                String classText = data.getStringExtra("classText");

                if (classText != null) {
                    study.setText(classText);
                }

            }
        }

    }
}
